<template>
  <div class="app-container">
    <div class="book-layout">
      <!-- 左侧栏：书名 + 目录 -->
      <div class="left-sidebar" ref="leftSidebar" :style="{ width: leftWidth + 'px' }">
        <div class="book-title">
          <h1>{{ formBookData.title }}</h1>
          <p class="subtitle">{{ formBookData.author }}</p>
        </div>
        <div class="chapter-list-container">
          <el-scrollbar height="calc(100vh - 280px)">
            <el-tree
              ref="chapterTree"
              :data="pageData"
              :props="treeProps"
              node-key="id"
              highlight-current
              @node-click="handleChapterClick"
              class="chapter-tree"
            />
          </el-scrollbar>
        </div>
        <div class="resize-handle left" @mousedown="startResize($event, 'left')"></div>
      </div>

      <!-- 中间栏：简介 + 内容 -->
      <div class="main-content" ref="mainContent">
        <div class="intro-section">
          <div class="header">
            <h2>简介</h2>
            <div class="info">{{ formBookData.abstracts }}</div>
            <el-button type="primary" size="small" @click="showAI = !showAI" class="toggle-ai-btn">
              {{ showAI ? "隐藏AI助手" : "显示AI助手" }}
            </el-button>
          </div>
        </div>
        <div class="content-section">
          <el-tabs type="border-card">
            <el-tab-pane label="简体">
              <div class="grid">
                <el-scrollbar height="calc(100vh - 280px)">
                  <div class="chapter-content" v-html="formAncientData.contentCn"></div>
                </el-scrollbar>
              </div>
            </el-tab-pane>
            <el-tab-pane label="繁体">
              <div class="grid">
                <el-scrollbar height="calc(100vh - 280px)">
                  <div class="chapter-content" v-html="formAncientData.contentTc"></div>
                </el-scrollbar>
              </div>
            </el-tab-pane>
            <el-tab-pane label="语译">
              <div class="grid">
                <el-scrollbar height="calc(100vh - 280px)">
                  <div class="chapter-content" v-html="formAncientData.content"></div>
                </el-scrollbar>
              </div>
            </el-tab-pane>
            <el-tab-pane label="处方">
              <div class="grid">
                <el-scrollbar height="calc(100vh - 280px)">
                  <ArticleTcm
                    :articleId="formAncientData.id"
                    :articleTitle="formAncientData.titleCn as string | undefined"
                    ref="articleTcmRef"
                  />
                </el-scrollbar>
              </div>
            </el-tab-pane>
          </el-tabs>
        </div>
      </div>

      <!-- 右侧栏：AI助手（可折叠） -->
      <div
        class="right-sidebar"
        v-show="showAI"
        ref="rightSidebar"
        :style="{ width: rightWidth + 'px' }"
      >
        <div class="resize-handle right" @mousedown="startResize($event, 'right')"></div>
        <Chat :articleId="formAncientData.id" />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { nextTick } from "vue";

defineOptions({
  name: "AncientTcm",
  inheritAttrs: false,
});
import ArticleAncientAPI, {
  ArticleAncientPageVO,
  ArticleAncientForm,
  ArticleAncientPageQuery,
} from "@/api/project/article-ancient";

import ArticleBookAPI, {
  ArticleBookPageVO,
  ArticleBookForm,
  ArticleBookPageQuery,
} from "@/api/project/article-book";

import ArticleTcm from "../components/ArticleTcm.vue";

const articleTcmRef = ref();
const chapterTree = ref();
const dataFormRef = ref(ElForm);
const loading = ref(false);
const removeIds = ref<number[]>([]);
const total = ref(0);

// 获取路由参数
const route = useRoute();
const bookId = ref(route.query.id as string);
const bookTitle = ref(route.query.title as string);

const treeProps = { label: "titleCn", children: "children" };

const queryParams = reactive<ArticleAncientPageQuery>({
  pageNum: 1,
  pageSize: 1000,
  importXmlId: Number(bookId.value),
});

// 古籍详情表格数据
const pageData = ref<ArticleAncientPageVO[]>([]);

// 控制AI助手显示
const showAI = ref(false);

// 侧边栏宽度
const leftWidth = ref(300);
const rightWidth = ref(350);
const minWidth = 200;
const maxWidth = 800;

// 引用DOM元素
const leftSidebar = ref<HTMLElement>();
const rightSidebar = ref<HTMLElement>();
const mainContent = ref<HTMLElement>();

// 拖动相关状态
const isResizing = ref(false);
const currentSide = ref("");
const startX = ref(0);
const startWidth = ref(0);

// 开始调整大小
const startResize = (e: MouseEvent, side: string) => {
  isResizing.value = true;
  currentSide.value = side;
  startX.value = e.clientX;
  startWidth.value = side === "left" ? leftWidth.value : rightWidth.value;

  document.addEventListener("mousemove", handleMouseMove);
  document.addEventListener("mouseup", stopResize);
  document.body.style.cursor = "col-resize";
  document.body.style.userSelect = "none";
};

// 处理鼠标移动
const handleMouseMove = (e: MouseEvent) => {
  if (!isResizing.value) return;

  const dx = e.clientX - startX.value;

  if (currentSide.value === "left") {
    const newWidth = Math.min(Math.max(startWidth.value + dx, minWidth), maxWidth);
    leftWidth.value = newWidth;
  } else {
    const newWidth = Math.min(Math.max(startWidth.value - dx, minWidth), maxWidth);
    rightWidth.value = newWidth;
  }
};

// 停止调整大小
const stopResize = () => {
  isResizing.value = false;
  document.removeEventListener("mousemove", handleMouseMove);
  document.removeEventListener("mouseup", stopResize);
  document.body.style.cursor = "";
  document.body.style.userSelect = "";
};

/** 查询古籍详情 */
function handleQuery() {
  loading.value = true;
  queryParams.importXmlId = Number(bookId.value);
  ArticleAncientAPI.getPage(queryParams)
    .then((data) => {
      pageData.value = data.list;
      total.value = data.total;
      console.log(111111);
      // Automatically select the first node if data exists
      if (data.list && data.list.length > 0) {
        nextTick(() => {
          chapterTree.value?.setCurrentKey(data.list[0].id);
          handleChapterClick(data.list[0]);
        });
      }
    })
    .finally(() => {
      loading.value = false;
    });
}

const formBookData = reactive<ArticleBookForm>({});
/** 查询古籍书 */
function handleBookQuery() {
  loading.value = true;
  ArticleBookAPI.getFormData(Number(bookId.value)).then((data) => {
    Object.assign(formBookData, data);
  });
}

// 当前选中章节
const currentChapter = ref(null);
const handleChapterClick = (data: any) => {
  currentChapter.value = data;
  handleOpenArticleAncient(data.id);
};

/** 打开古籍详情 */
const formAncientData = reactive<ArticleAncientForm>({});
function handleOpenArticleAncient(id: number) {
  ArticleAncientAPI.getFormData(id).then((data) => {
    Object.assign(formAncientData, data);
  });
}

// 监听路由参数变化
watch(
  () => [route.query.id],
  ([id]) => {
    queryParams.importXmlId = Number(id);
    bookId.value = id as string;
    handleQuery();
    handleBookQuery();
  },
  { immediate: true }
);

onMounted(() => {
  handleQuery();
  handleBookQuery();
});
</script>

<style scoped>
.book-layout {
  display: flex;
  height: 88vh;
  overflow: hidden;
}

.left-sidebar {
  position: relative;
  background: #f8f9fa;
  flex-shrink: 0;
  height: 100%;
}

.book-title {
  padding: 10px 0 20px;
  text-align: center;
  border-bottom: 1px solid #e4e7ed;
  height: 100px;
}
.book-title h1 {
  margin: 0;
  font-size: 24px;
  color: #333;
}
.subtitle {
  margin: 5px 0 0;
  color: #666;
  font-style: italic;
}

.chapter-tree {
  background: transparent;
}
:deep(.chapter-tree .el-tree-node__content) {
  height: 40px;
}

.main-content {
  flex-grow: 1;
  min-width: 0;
  overflow: hidden;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 98px;
  border-left: 1px solid #ebeef5;
}
.header h2 {
  margin: 10px;
  width: 30px;
}
.info {
  text-align: left;
  margin-top: 0;
  line-height: 1.5;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
  max-height: calc(1.5em * 3);
}

.toggle-ai-btn {
  margin-left: 15px;
}

.intro-section p {
  line-height: 1.8;
  color: #444;
}

.content-section {
  margin-top: 1px;
}
.chapter-content {
  padding: 15px;
  line-height: 1.8;
  white-space: pre-wrap;
}

/* 右侧栏样式 */
.right-sidebar {
  position: relative;
  flex-shrink: 0;
  height: 100%;
  overflow: hidden;
  border-left: 1px solid #ebeef5;
  background: #fafafa;
}

/* 调整大小的手柄 */
.resize-handle {
  position: absolute;
  top: 0;
  width: 5px;
  height: 100%;
  cursor: col-resize;
  z-index: 10;
}

.resize-handle.left {
  right: -2px;
}

.resize-handle.right {
  left: -2px;
}

.resize-handle:hover,
.resize-handle.active {
  background-color: #409eff;
}
</style>
